package com.nnnu.wsnackshop.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nnnu.wsnackshop.constant.MessageConstants;
import com.nnnu.wsnackshop.exception.BaseException;
import com.nnnu.wsnackshop.mapper.ActivityLogsMapper;
import com.nnnu.wsnackshop.mapper.MembersMapper;
import com.nnnu.wsnackshop.mapper.UsersMapper;
import com.nnnu.wsnackshop.pojo.dto.LoginDTO;
import com.nnnu.wsnackshop.pojo.dto.WechatLoginDTO;
import com.nnnu.wsnackshop.pojo.dto.WechatPhoneLoginDTO;
import com.nnnu.wsnackshop.pojo.dto.PhoneLoginDTO;
import com.nnnu.wsnackshop.pojo.dto.SendSmsCodeDTO;
import com.nnnu.wsnackshop.pojo.entity.Members;
import com.nnnu.wsnackshop.pojo.entity.Riders;
import com.nnnu.wsnackshop.pojo.entity.Users;
import com.nnnu.wsnackshop.pojo.vo.CouponVO;
import com.nnnu.wsnackshop.pojo.vo.WechatLoginVO;
import com.nnnu.wsnackshop.service.AuthService;
import com.nnnu.wsnackshop.service.IRidersService;
import com.nnnu.wsnackshop.service.IUserCouponsService;
import com.nnnu.wsnackshop.utils.JwtUtil;
import com.nnnu.wsnackshop.utils.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.shiro.authc.AuthenticationException;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    // 注入ApplicationContext来获取代理对象
    @Autowired
    private ApplicationContext applicationContext;

    // 用于存储代理对象的引用
    private AuthService self;

    private final UsersMapper userMapper;
    private final MembersMapper membersMapper;
    private final WxMaService wxMaService;
    private final StringRedisTemplate stringRedisTemplate;
    private final IUserCouponsService userCouponsService;
    private final IRidersService ridersService;

    // 使用构造器注入
    public AuthServiceImpl(UsersMapper userMapper,
            MembersMapper membersMapper, WxMaService wxMaService,
            StringRedisTemplate stringRedisTemplate,
            IUserCouponsService userCouponsService,
            IRidersService ridersService) {
        this.userMapper = userMapper;
        this.membersMapper = membersMapper;
        this.wxMaService = wxMaService;
        this.stringRedisTemplate = stringRedisTemplate;
        this.userCouponsService = userCouponsService;
        this.ridersService = ridersService;
    }

    // 在初始化后获取代理对象
    @PostConstruct
    public void init() {
        // 获取Spring容器中的代理对象
        self = applicationContext.getBean(AuthService.class);
    }

    @Override
    public String login(@NotNull LoginDTO loginDTO) {
        Users user = userMapper.selectOne(
                new LambdaQueryWrapper<Users>().eq(Users::getUsername, loginDTO.getUsername()));
        if (user == null || !PasswordUtil.verify(loginDTO.getPassword(), user.getPassword())) {
            throw new AuthenticationException("用户名或密码错误");
        }
        // 生成 JWT，使用含有用户信息的token
        return JwtUtil.createTokenWithUser(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public WechatLoginVO wechatLogin(WechatLoginDTO wechatLoginDTO) {
        log.info("开始处理微信小程序登录请求，code={}", wechatLoginDTO.getCode());
        String code = wechatLoginDTO.getCode();
        WxMaJscode2SessionResult sessionInfo;
        try {
            sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            log.info("获取微信session信息成功: sessionKey={}, openid={}", sessionInfo.getSessionKey(), sessionInfo.getOpenid());
        } catch (WxErrorException e) {
            log.error("获取微信session信息失败: {}", e.getMessage());
            throw new BaseException(MessageConstants.WECHAT_AUTH_FAILED);
        }

        String openid = sessionInfo.getOpenid();
        if (openid == null) {
            log.error("获取openid失败");
            throw new BaseException(MessageConstants.WECHAT_AUTH_FAILED);
        }

        log.info("通过openid={}查询用户", openid);
        Members member = membersMapper.selectOne(new LambdaQueryWrapper<Members>().eq(Members::getOpenid, openid));
        WechatLoginVO loginResult;
        boolean isNewUser = false;

        if (member == null) {
            log.info("未找到关联用户，准备创建新用户");
            // 新用户，自动注册
            Users newUser = new Users();
            // 生成唯一用户名，例如 "wx_" + 随机字符串
            String username = "wx_" + generateRandomString(8);
            newUser.setUsername(username);
            newUser.setPassword(PasswordUtil.hash("123456")); // 默认密码，微信登录不通过密码认证
            newUser.setStatus(1); // 设置用户状态为启用

            // 设置微信用户信息
            if (wechatLoginDTO.getNickName() != null && !wechatLoginDTO.getNickName().trim().isEmpty()) {
                newUser.setNickname(wechatLoginDTO.getNickName());
            } else {
                newUser.setNickname("微信用户" + generateRandomString(4));
            }

            if (wechatLoginDTO.getAvatarUrl() != null && !wechatLoginDTO.getAvatarUrl().trim().isEmpty()) {
                newUser.setAvatar(wechatLoginDTO.getAvatarUrl());
            }

            log.info("准备插入新用户: {}", newUser);
            int insertResult = userMapper.insert(newUser);
            log.info("用户插入完成，插入结果: {}, 用户ID: {}", insertResult, newUser.getId());

            // 确保获取到生成的用户ID
            Integer userId = newUser.getId();
            if (userId == null) {
                log.error("用户创建失败，无法获取用户ID，尝试重新查询用户");
                // 尝试通过用户名重新查询用户来获取ID
                Users insertedUser = userMapper.selectOne(
                        new LambdaQueryWrapper<Users>().eq(Users::getUsername, username));
                if (insertedUser != null) {
                    userId = insertedUser.getId();
                    log.info("通过用户名重新查询获取到用户ID: {}", userId);
                } else {
                    throw new BaseException("用户创建失败，无法获取用户ID");
                }
            }
            log.info("获取到用户ID: {}", userId);

            Members newMember = new Members();
            newMember.setUserId(userId);
            newMember.setOpenid(openid);
            newMember.setNickname(newUser.getNickname());
            newMember.setGender(wechatLoginDTO.getGender());
            newMember.setAvatar(wechatLoginDTO.getAvatarUrl());
            newMember.setStatus(1);
            newMember.setCreatedAt(LocalDateTime.now());
            newMember.setUpdatedAt(LocalDateTime.now());

            log.info("准备插入新会员: {}", newMember);
            membersMapper.insert(newMember);
            log.info("会员插入完成");

            String token = JwtUtil.createTokenWithUser(newUser);
            loginResult = WechatLoginVO.builder()
                    .token(token)
                    .userInfo(newMember)
                    .newUserCoupons(new ArrayList<>()) // 确保初始化为空列表
                    .build();
            isNewUser = true;

        } else {
            log.info("找到现有会员信息，用户ID={}", member.getUserId());
            // 老用户，登录但不更新用户信息
            Users existingUser = userMapper.selectById(member.getUserId());
            if (existingUser == null) {
                log.error("关联用户不存在，会员ID={}, 用户ID={}", member.getId(), member.getUserId());
                throw new BaseException("关联用户不存在"); // 数据不一致情况
            }

            // 直接使用已有的用户信息进行登录
            String token = JwtUtil.createTokenWithUser(existingUser);
            loginResult = WechatLoginVO.builder()
                    .token(token)
                    .userInfo(member)
                    .newUserCoupons(new ArrayList<>()) // 确保初始化为空列表
                    .build();
            log.info("老用户登录成功，token已生成");
        }

        // 如果是新用户，尝试发放新人优惠券
        if (isNewUser) {
            log.info("是新用户，使用异步方式发放新人优惠券");
            try {
                // 异步处理发券，不阻塞登录流程
                userCouponsService.issueNewUserCouponsAsync(loginResult.getUserInfo().getUserId());
                // 直接设置空列表，异步过程中不返回优惠券信息
                loginResult.setNewUserCoupons(new ArrayList<>());
                log.info("新人优惠券异步发放已启动，实际数量将在后台处理");
            } catch (Exception e) {
                log.error("启动异步发券任务异常: {}", e.getMessage(), e);
                loginResult.setNewUserCoupons(new ArrayList<>());
            }
        }

        log.info("微信登录处理完成，准备返回登录结果");
        return loginResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public List<CouponVO> processNewUserCoupons(Integer userId) {
        log.info("开始在独立事务中处理新人优惠券，用户ID={}", userId);
        try {
            return userCouponsService.issueNewUserCoupons(userId);
        } catch (Exception e) {
            log.error("发券异常捕获: {}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional
    public WechatLoginVO wechatPhoneLogin(WechatPhoneLoginDTO wechatPhoneLoginDTO) {
        String code = wechatPhoneLoginDTO.getCode();
        WxMaPhoneNumberInfo phoneNumberInfo;
        try {
            // Use the simplified getPhoneNumber method directly with the code
            phoneNumberInfo = wxMaService.getUserService().getPhoneNumber(code);
        } catch (WxErrorException e) {
            log.error("获取微信手机号信息失败: {}", e.getMessage());
            throw new BaseException(MessageConstants.WECHAT_PHONE_AUTH_FAILED);
        }

        String phoneNumber = phoneNumberInfo.getPhoneNumber();
        if (phoneNumber == null) {
            throw new BaseException(MessageConstants.WECHAT_PHONE_AUTH_FAILED);
        }

        // 检查用户表中是否已存在该手机号
        Users existingUserByPhone = userMapper
                .selectOne(new LambdaQueryWrapper<Users>().eq(Users::getPhone, phoneNumber));

        Members member;
        Users userToLogin;
        boolean isNewUser = false;

        if (existingUserByPhone == null) {
            // 如果手机号不存在，则自动注册新用户
            Users newUser = new Users();
            String username = "phone_" + phoneNumber; // 使用手机号作为用户名
            newUser.setUsername(username);
            newUser.setPassword(PasswordUtil.hash("123456")); // 默认密码
            newUser.setPhone(phoneNumber); // 设置手机号
            newUser.setNickname("手机用户" + phoneNumber.substring(7)); // 默认昵称，后四位手机号
            newUser.setStatus(1); // 设置用户状态为启用

            log.info("准备插入新用户(手机号登录): {}", newUser);
            int insertResult = userMapper.insert(newUser);
            log.info("用户插入完成(手机号登录)，插入结果: {}, 用户ID: {}", insertResult, newUser.getId());

            // 确保获取到生成的用户ID
            Integer userId = newUser.getId();
            if (userId == null) {
                log.error("用户创建失败(手机号登录)，无法获取用户ID，尝试重新查询用户");
                // 尝试通过用户名重新查询用户来获取ID
                Users insertedUser = userMapper.selectOne(
                        new LambdaQueryWrapper<Users>().eq(Users::getUsername, username));
                if (insertedUser != null) {
                    userId = insertedUser.getId();
                    log.info("通过用户名重新查询获取到用户ID(手机号登录): {}", userId);
                } else {
                    throw new BaseException("用户创建失败，无法获取用户ID");
                }
            }

            Members newMember = getMembers(userId, phoneNumber);
            membersMapper.insert(newMember);

            userToLogin = newUser;
            member = newMember;
            isNewUser = true;

        } else {
            // 如果手机号已存在，则直接登录
            userToLogin = existingUserByPhone;
            member = membersMapper
                    .selectOne(new LambdaQueryWrapper<Members>().eq(Members::getUserId, userToLogin.getId()));

            if (member == null) {
                // 理论上不会发生，如果user存在但member不存在，则创建member
                member = new Members();
                member.setUserId(userToLogin.getId());
                member.setNickname(
                        userToLogin.getNickname() != null ? userToLogin.getNickname() : userToLogin.getUsername()); // 使用昵称或用户名
                member.setStatus(1);
                membersMapper.insert(member);
            }
        }

        String token = JwtUtil.createTokenWithUser(userToLogin);
        WechatLoginVO loginResult = WechatLoginVO.builder()
                .token(token)
                .userInfo(member)
                .newUserCoupons(new ArrayList<>()) // 空列表，优惠券将异步发放
                .build();

        // 如果是新用户，尝试发放新人优惠券
        if (isNewUser) {
            try {
                // 使用代理对象调用，确保事务生效
                List<CouponVO> coupons = self.issueNewUserCoupons(member.getUserId());
                loginResult.setNewUserCoupons(coupons); // 设置新人优惠券到响应对象
            } catch (Exception e) {
                log.error("为用户{}发放新人券失败: {}", member.getUserId(), e.getMessage());
                // 优惠券发放失败不影响登录流程
                loginResult.setNewUserCoupons(new ArrayList<>());
            }
        }

        return loginResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<CouponVO> issueNewUserCoupons(Integer userId) {
        log.info("开始为用户{}发放新人优惠券", userId);
        // 委托给UserCouponsService处理
        List<CouponVO> coupons = userCouponsService.issueNewUserCoupons(userId);
        log.info("用户{}新人优惠券发放完成，券数量: {}", userId, coupons.size());
        return coupons;
    }

    private Members getMembers(Integer userId, String phoneNumber) {
        Members newMember = new Members();
        newMember.setUserId(userId);
        newMember.setNickname("手机用户" + phoneNumber.substring(7)); // 默认昵称，后四位手机号
        newMember.setStatus(1);
        newMember.setCreatedAt(LocalDateTime.now());
        newMember.setUpdatedAt(LocalDateTime.now());
        return newMember;
    }

    // 辅助方法：生成随机字符串
    private String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder result = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            result.append(characters.charAt(random.nextInt(characters.length())));
        }
        return result.toString();
    }

    @Override
    public boolean sendSmsCode(SendSmsCodeDTO sendSmsCodeDTO) {
        String phone = sendSmsCodeDTO.getPhone();
        log.info("开始为手机号{}发送验证码", phone);

        // 检查是否频繁发送
        String countKey = "sms:count:" + phone;
        String limitKey = "sms:limit:" + phone;

        // 检查是否被限制发送（1小时内超过5次）
        Boolean isLimited = stringRedisTemplate.hasKey(limitKey);
        if (Boolean.TRUE.equals(isLimited)) {
            log.warn("手机号{}短信发送过于频繁，已被限制", phone);
            throw new BaseException("短信发送过于频繁，请稍后再试");
        }

        // 检查当前已发送次数
        String countStr = stringRedisTemplate.opsForValue().get(countKey);
        int count = countStr != null ? Integer.parseInt(countStr) : 0;
        if (count >= 5) {
            // 设置限制，1小时内不能再发送
            stringRedisTemplate.opsForValue().set(limitKey, "1", 1, TimeUnit.HOURS);
            log.warn("手机号{}短信发送超过5次，已被限制1小时", phone);
            throw new BaseException("短信发送次数超限，请1小时后再试");
        }

        // 生成6位随机验证码
        String code = generateVerificationCode();
        String codeKey = "sms:code:" + phone;

        // 实际项目中，这里需要调用第三方短信服务发送短信
        // 在这里模拟短信发送成功
        log.info("模拟向手机号{}发送验证码: {}", phone, code);

        // 将验证码存入Redis，设置有效期5分钟
        stringRedisTemplate.opsForValue().set(codeKey, code, 5, TimeUnit.MINUTES);

        // 记录发送次数，24小时有效
        stringRedisTemplate.opsForValue().increment(countKey, 1);
        if (count == 0) {
            stringRedisTemplate.expire(countKey, 24, TimeUnit.HOURS);
        }

        log.info("手机号{}验证码发送成功", phone);
        return true;
    }

    @Override
    @Transactional
    public WechatLoginVO phoneLogin(PhoneLoginDTO phoneLoginDTO) {
        String phone = phoneLoginDTO.getPhone();
        String code = phoneLoginDTO.getCode();
        log.info("开始处理手机号登录请求，手机号={}", phone);

        // 验证短信验证码
        String codeKey = "sms:code:" + phone;
        String savedCode = stringRedisTemplate.opsForValue().get(codeKey);

        if (savedCode == null) {
            log.warn("手机号{}的验证码不存在或已过期", phone);
            throw new BaseException("验证码已过期，请重新获取");
        }

        if (!savedCode.equals(code)) {
            log.warn("手机号{}提交的验证码错误", phone);
            throw new BaseException("验证码错误");
        }

        // 验证通过后，删除验证码，防止重复使用
        stringRedisTemplate.delete(codeKey);

        // 获取openid（可能为null）
        String openid = phoneLoginDTO.getOpenid();

        // 首先检查是否已存在该手机号的用户
        Users existingUserByPhone = userMapper
                .selectOne(new LambdaQueryWrapper<Users>().eq(Users::getPhone, phone));

        // 如果提供了openid，检查是否存在该openid的会员
        Members existingMemberByOpenid = null;
        if (openid != null && !openid.isEmpty()) {
            log.info("检查openid={}是否已存在会员记录", openid);
            existingMemberByOpenid = membersMapper.selectOne(
                    new LambdaQueryWrapper<Members>().eq(Members::getOpenid, openid));
        }

        Members member = null;
        Users userToLogin = null;
        boolean isNewUser = false;

        // 情况1：通过openid找到了已存在的会员
        if (existingMemberByOpenid != null) {
            log.info("已找到openid={}对应的会员记录，会员ID={}", openid, existingMemberByOpenid.getId());

            // 找到用户记录
            Users existingUser = userMapper.selectById(existingMemberByOpenid.getUserId());
            if (existingUser != null) {
                // 更新用户手机号（如果之前没有设置过）
                if (existingUser.getPhone() == null || existingUser.getPhone().isEmpty()) {
                    existingUser.setPhone(phone);
                    userMapper.updateById(existingUser);
                    log.info("已为微信用户ID={}更新手机号={}", existingUser.getId(), phone);
                } else if (!existingUser.getPhone().equals(phone)) {
                    // 如果用户已有手机号，但与当前登录手机号不同，则更新为新手机号
                    log.info("用户ID={}更新手机号: {} -> {}", existingUser.getId(), existingUser.getPhone(), phone);
                    existingUser.setPhone(phone);
                    userMapper.updateById(existingUser);
                }

                userToLogin = existingUser;
                member = existingMemberByOpenid;
            }
        }
        // 情况2：通过手机号找到了已存在的用户，但没有通过openid找到会员
        else if (existingUserByPhone != null) {
            log.info("已找到手机号={}对应的用户记录，用户ID={}", phone, existingUserByPhone.getId());
            userToLogin = existingUserByPhone;

            // 查找该用户对应的会员记录
            member = membersMapper.selectOne(
                    new LambdaQueryWrapper<Members>().eq(Members::getUserId, userToLogin.getId()));

            if (member != null) {
                // 如果会员记录存在且提供了openid，但会员没有openid，则更新会员的openid
                if (openid != null && !openid.isEmpty()
                        && (member.getOpenid() == null || member.getOpenid().isEmpty())) {
                    member.setOpenid(openid);
                    membersMapper.updateById(member);
                    log.info("已为会员ID={}更新openid={}", member.getId(), openid);
                }
            } else {
                // 如果用户存在但会员记录不存在，创建新会员记录
                member = new Members();
                member.setUserId(userToLogin.getId());
                member.setNickname(
                        userToLogin.getNickname() != null ? userToLogin.getNickname() : userToLogin.getUsername());
                member.setStatus(1);

                // 如果有openid，设置到会员信息中
                if (openid != null && !openid.isEmpty()) {
                    member.setOpenid(openid);
                    log.info("为新创建的会员设置openid={}", openid);
                }

                membersMapper.insert(member);
                log.info("为用户ID={}创建了新的会员记录", userToLogin.getId());
            }
        }
        // 情况3：既没有通过openid也没有通过手机号找到用户，创建新用户
        else {
            log.info("未找到手机号={}或openid={}的用户记录，将创建新用户", phone, openid);
            isNewUser = true;

            // 创建新用户
            Users newUser = new Users();
            String username = "phone_" + phone; // 使用手机号作为用户名
            newUser.setUsername(username);
            newUser.setPassword(PasswordUtil.hash("123456")); // 默认密码
            newUser.setPhone(phone); // 设置手机号
            newUser.setNickname("手机用户" + phone.substring(7)); // 默认昵称，后四位手机号
            newUser.setStatus(1); // 设置用户状态为启用

            log.info("准备插入新用户: {}", newUser);
            userMapper.insert(newUser);
            log.info("用户插入完成，用户ID: {}", newUser.getId());

            // 创建新会员
            member = new Members();
            member.setUserId(newUser.getId());
            member.setNickname(newUser.getNickname());
            member.setStatus(1);

            // 如果有openid，设置到会员信息中
            if (openid != null && !openid.isEmpty()) {
                member.setOpenid(openid);
                log.info("为新会员设置openid={}", openid);
            }

            membersMapper.insert(member);
            log.info("会员插入完成，会员ID: {}", member.getId());

            userToLogin = newUser;
        }

        // 创建登录响应，不包含优惠券
        WechatLoginVO loginResult = createLoginResponseWithoutCoupons(userToLogin, member);

        // 如果是新用户，异步发放新人优惠券
        if (isNewUser) {
            final Integer userId = member.getUserId();
            log.info("新用户登录，将异步发放新人优惠券，用户ID={}", userId);

            // 使用异步方式发放优惠券，避免影响登录流程
            try {
                userCouponsService.issueNewUserCouponsAsync(userId);
            } catch (Exception e) {
                log.error("启动异步发券任务异常: {}", e.getMessage(), e);
                // 异常不影响登录流程
            }
        }

        log.info("登录处理完成，准备返回登录结果");
        return loginResult;
    }

    // 创建不包含优惠券的登录响应
    private WechatLoginVO createLoginResponseWithoutCoupons(Users user, Members member) {
        String token = JwtUtil.createTokenWithUser(user);
        return WechatLoginVO.builder()
                .token(token)
                .userInfo(member)
                .newUserCoupons(new ArrayList<>()) // 空列表，优惠券将异步发放
                .build();
    }

    /**
     * 生成6位数字验证码
     */
    private @NotNull String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    @Override
    public String getWechatOpenid(String code) {
        try {
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            return sessionInfo.getOpenid();
        } catch (WxErrorException e) {
            log.error("获取微信openid失败: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public String refreshToken(String oldToken) {
        if (oldToken == null || oldToken.isEmpty()) {
            log.warn("刷新token失败：传入的token为空");
            return null;
        }

        try {
            // 验证token是否在黑名单中
            if (stringRedisTemplate != null
                    && Boolean.TRUE.equals(stringRedisTemplate.hasKey("token_blacklist:" + oldToken))) {
                log.warn("刷新token失败：token已在黑名单中");
                return null;
            }

            // 从token中获取用户信息
            String username = JwtUtil.getUsername(oldToken);
            if (username == null) {
                log.warn("刷新token失败：无法从token中获取用户名");
                return null;
            }

            // 获取用户类型
            String userType = JwtUtil.getUserTypeFromToken(oldToken);

            if ("rider".equals(userType)) {
                // 骑手token刷新
                Riders rider = JwtUtil.getRiderFromToken(oldToken);
                if (rider == null) {
                    // 如果token中没有骑手信息，则从数据库查询
                    LambdaQueryWrapper<Riders> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(Riders::getPhone, username);
                    rider = ridersService.getOne(queryWrapper);
                }

                if (rider == null) {
                    log.warn("刷新token失败：骑手不存在");
                    return null;
                }

                // 生成新token
                return JwtUtil.createTokenWithRider(rider);
            } else {
                // 普通用户token刷新
                Users user = JwtUtil.getUserFromToken(oldToken);
                if (user == null) {
                    // 如果token中没有用户信息，则从数据库查询
                    user = userMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername, username));
                }

                if (user == null) {
                    log.warn("刷新token失败：用户不存在");
                    return null;
                }

                // 生成新token
                return JwtUtil.createTokenWithUser(user);
            }
        } catch (Exception e) {
            log.error("刷新token时发生异常", e);
            return null;
        }
    }
}
